package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileLockExample3 {
    public static void main(String[] args)  {

        File file = new File("example.txt");

        FileLock fileLock = null;
        try ( FileChannel fileChannel = FileChannel.open(Paths.get("example.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);
        ){

            fileLock = fileChannel.tryLock();

            Thread.sleep(10000);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(fileLock != null){
                    fileLock.release();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        new Thread(() ->{
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("example.txt")))){
                String line;
                while((line = bufferedReader.readLine()) != null){
                    System.out.println(line);
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();

    }
}